/*
 * @Author: lixu lixu@puchigames.com
 * @Date: 2025-09-18 11:25:00
 * @LastEditors: lixu lixu@puchigames.com
 * @LastEditTime: 2025-09-18 11:25:00
 * @FilePath: /go-helper/ixLog/logger.go
 * @Description: 核心日志器实现，提供完整的日志功能
 */

package ixLog

import (
	"context"
	"fmt"
	"os"
	"sync"
	"sync/atomic"
	"time"
)

// ixLogger 日志器实现
type ixLogger struct {
	config       *Config
	formatter    Formatter
	writer       Writer
	traceManager *TraceManager
	sanitizer    *Sanitizer
	hooks        []Hook
	stats        *Stats

	// 运行时状态
	level     int32 // 原子操作的日志级别
	running   int32 // 是否运行中
	startTime time.Time

	// 异步处理
	entryPool   sync.Pool
	flushTicker *time.Ticker
	stopChan    chan struct{}

	// 线程安全
	mutex sync.RWMutex
}

// NewLogger 创建新的日志器
func NewLogger(options ...ConfigOption) (Logger, error) {
	config := NewConfig(options...)

	if err := ValidateConfig(config); err != nil {
		return nil, fmt.Errorf("配置验证失败: %w", err)
	}

	logger := &ixLogger{
		config:    config,
		startTime: time.Now(),
		stopChan:  make(chan struct{}),
		stats: &Stats{
			LevelCounts: make(map[LogLevel]int64),
		},
	}

	// 设置日志级别
	atomic.StoreInt32(&logger.level, int32(config.Level))

	// 初始化格式化器
	logger.formatter = GetFormatter(config)

	// 初始化写入器
	if err := logger.initWriter(); err != nil {
		return nil, fmt.Errorf("初始化写入器失败: %w", err)
	}

	// 初始化追踪管理器
	if config.EnableTrace {
		logger.traceManager = NewTraceManager(config)
	}

	// 初始化脱敏器
	if config.EnableSanitize {
		logger.sanitizer = NewSanitizer(config.SanitizeFields, config.SanitizePatterns)
	}

	// 初始化对象池
	logger.entryPool = sync.Pool{
		New: func() interface{} {
			return &LogEntry{
				Fields: make(map[string]interface{}),
			}
		},
	}

	// 启动异步刷新
	if config.EnableAsync {
		logger.startFlushTicker()
	}

	atomic.StoreInt32(&logger.running, 1)
	return logger, nil
}

// initWriter 初始化写入器
func (l *ixLogger) initWriter() error {
	var writers []Writer

	for _, outputConfig := range l.config.Outputs {
		if !outputConfig.Enable {
			continue
		}

		writer, err := CreateWriter(&outputConfig)
		if err != nil {
			return fmt.Errorf("创建写入器失败: %w", err)
		}

		// 根据配置包装写入器
		if l.config.EnableAsync && outputConfig.Type != ConsoleTarget {
			writer = NewAsyncWriter(writer, l.config.BufferSize, false)
		} else if l.config.BufferSize > 0 {
			writer = NewBufferedWriter(writer, l.config.BufferSize)
		}

		writers = append(writers, writer)
	}

	if len(writers) == 0 {
		return fmt.Errorf("没有可用的写入器")
	}

	if len(writers) == 1 {
		l.writer = writers[0]
	} else {
		l.writer = NewMultiWriter(writers...)
	}

	return nil
}

// startFlushTicker 启动刷新定时器
func (l *ixLogger) startFlushTicker() {
	l.flushTicker = time.NewTicker(l.config.FlushInterval)

	go func() {
		for {
			select {
			case <-l.flushTicker.C:
				l.Flush()
			case <-l.stopChan:
				return
			}
		}
	}()
}

// log 核心日志方法
func (l *ixLogger) log(level LogLevel, msg string, fields map[string]interface{}, err error, ctx context.Context) {
	// 检查日志级别
	if !l.IsLevelEnabled(level) {
		return
	}

	// 检查是否运行中
	if atomic.LoadInt32(&l.running) == 0 {
		return
	}

	// 获取日志条目
	entry := l.getLogEntry()
	defer l.putLogEntry(entry)

	// 基础信息
	entry.Timestamp = time.Now()
	entry.Level = level
	entry.Message = msg
	entry.Error = err

	// 复制字段
	if len(fields) > 0 {
		for k, v := range fields {
			entry.Fields[k] = v
		}
	}

	// 添加全局字段
	for k, v := range l.config.GlobalFields {
		if _, exists := entry.Fields[k]; !exists {
			entry.Fields[k] = v
		}
	}

	// 添加应用信息
	if l.config.AppName != "" {
		entry.Fields["app"] = l.config.AppName
	}
	if l.config.Environment != "" {
		entry.Fields["env"] = l.config.Environment
	}
	if l.config.Hostname != "" {
		entry.Fields["host"] = l.config.Hostname
	}

	// 获取追踪信息
	if ctx != nil {
		if traceCtx := GetTraceContext(ctx); traceCtx != nil {
			entry.TraceID = traceCtx.TraceID
			entry.SpanID = traceCtx.SpanID
			entry.ParentSpanID = traceCtx.ParentSpanID

			// 添加Baggage
			for k, v := range traceCtx.Baggage {
				entry.Fields[k] = v
			}
		}
	}

	// 获取调用者信息
	if l.config.EnableCaller {
		entry.Caller = GetCallerInfo(l.config.CallerSkip)
	}

	// 获取调用栈（仅对TRACE和ERROR级别）
	if (level == TRACE || level == ERROR) && l.config.StackDepth > 0 {
		entry.Stack = GetCallStack(l.config.CallerSkip, l.config.StackDepth)
	}

	// 脱敏处理
	if l.sanitizer != nil {
		l.sanitizer.Sanitize(entry)
	}

	// 执行钩子
	if l.config.EnableHooks {
		l.executeHooks(entry)
	}

	// 格式化并写入
	if err := l.writeEntry(entry); err != nil {
		// 写入失败，输出到stderr
		fmt.Fprintf(os.Stderr, "日志写入失败: %v\n", err)
	}

	// 更新统计
	l.updateStats(entry)

	// FATAL级别自动退出
	if level == FATAL {
		l.Close()
		os.Exit(1)
	}
}

// writeEntry 写入日志条目
func (l *ixLogger) writeEntry(entry *LogEntry) error {
	data, err := l.formatter.Format(entry)
	if err != nil {
		return fmt.Errorf("格式化失败: %w", err)
	}

	_, err = l.writer.Write(data)
	return err
}

// getLogEntry 获取日志条目对象
func (l *ixLogger) getLogEntry() *LogEntry {
	entry := l.entryPool.Get().(*LogEntry)

	// 重置字段
	entry.Timestamp = time.Time{}
	entry.Level = INFO
	entry.Message = ""
	entry.TraceID = ""
	entry.SpanID = ""
	entry.ParentSpanID = ""
	entry.Caller = nil
	entry.Stack = nil
	entry.Error = nil

	// 清空字段映射
	for k := range entry.Fields {
		delete(entry.Fields, k)
	}

	return entry
}

// putLogEntry 归还日志条目对象
func (l *ixLogger) putLogEntry(entry *LogEntry) {
	l.entryPool.Put(entry)
}

// updateStats 更新统计信息
func (l *ixLogger) updateStats(entry *LogEntry) {
	atomic.AddInt64(&l.stats.TotalEntries, 1)

	// 使用锁保护LevelCounts的并发访问
	l.mutex.Lock()
	if l.stats.LevelCounts == nil {
		l.stats.LevelCounts = make(map[LogLevel]int64)
	}
	l.stats.LevelCounts[entry.Level]++
	l.stats.LastFlush = time.Now()
	l.stats.Uptime = time.Since(l.startTime)
	l.mutex.Unlock()

	if entry.Level == ERROR || entry.Level == FATAL {
		atomic.AddInt64(&l.stats.ErrorCount, 1)
	}
}

// executeHooks 执行钩子
func (l *ixLogger) executeHooks(entry *LogEntry) {
	l.mutex.RLock()
	defer l.mutex.RUnlock()

	for _, hook := range l.hooks {
		// 检查钩子是否关注当前级别
		levels := hook.Levels()
		interested := false
		for _, level := range levels {
			if level == entry.Level {
				interested = true
				break
			}
		}

		if interested {
			if err := hook.Fire(entry); err != nil {
				// 钩子执行失败，记录到stderr
				fmt.Fprintf(os.Stderr, "钩子执行失败: %v\n", err)
			}
		}
	}
}

// 实现Logger接口的基础日志方法
func (l *ixLogger) Trace(args ...interface{}) {
	l.log(TRACE, fmt.Sprint(args...), nil, nil, nil)
}

func (l *ixLogger) Tracef(format string, args ...interface{}) {
	l.log(TRACE, fmt.Sprintf(format, args...), nil, nil, nil)
}

func (l *ixLogger) Debug(args ...interface{}) {
	l.log(DEBUG, fmt.Sprint(args...), nil, nil, nil)
}

func (l *ixLogger) Debugf(format string, args ...interface{}) {
	l.log(DEBUG, fmt.Sprintf(format, args...), nil, nil, nil)
}

func (l *ixLogger) Info(args ...interface{}) {
	l.log(INFO, fmt.Sprint(args...), nil, nil, nil)
}

func (l *ixLogger) Infof(format string, args ...interface{}) {
	l.log(INFO, fmt.Sprintf(format, args...), nil, nil, nil)
}

func (l *ixLogger) Warn(args ...interface{}) {
	l.log(WARN, fmt.Sprint(args...), nil, nil, nil)
}

func (l *ixLogger) Warnf(format string, args ...interface{}) {
	l.log(WARN, fmt.Sprintf(format, args...), nil, nil, nil)
}

func (l *ixLogger) Error(args ...interface{}) {
	l.log(ERROR, fmt.Sprint(args...), nil, nil, nil)
}

func (l *ixLogger) Errorf(format string, args ...interface{}) {
	l.log(ERROR, fmt.Sprintf(format, args...), nil, nil, nil)
}

func (l *ixLogger) Fatal(args ...interface{}) {
	l.log(FATAL, fmt.Sprint(args...), nil, nil, nil)
}

func (l *ixLogger) Fatalf(format string, args ...interface{}) {
	l.log(FATAL, fmt.Sprintf(format, args...), nil, nil, nil)
}

// 实现Logger接口的上下文方法
func (l *ixLogger) WithContext(ctx context.Context) Logger {
	return &contextLogger{
		logger: l,
		ctx:    ctx,
	}
}

func (l *ixLogger) WithField(key string, value interface{}) Logger {
	return &fieldLogger{
		logger: l,
		fields: map[string]interface{}{key: value},
	}
}

func (l *ixLogger) WithFields(fields map[string]interface{}) Logger {
	return &fieldLogger{
		logger: l,
		fields: fields,
	}
}

func (l *ixLogger) WithError(err error) Logger {
	return &errorLogger{
		logger: l,
		err:    err,
	}
}

func (l *ixLogger) WithTrace(traceID, spanID, parentSpanID string) Logger {
	return &traceLogger{
		logger:       l,
		traceID:      traceID,
		spanID:       spanID,
		parentSpanID: parentSpanID,
	}
}

// 实现Logger接口的配置方法
func (l *ixLogger) SetLevel(level LogLevel) {
	atomic.StoreInt32(&l.level, int32(level))
}

func (l *ixLogger) GetLevel() LogLevel {
	return LogLevel(atomic.LoadInt32(&l.level))
}

func (l *ixLogger) IsLevelEnabled(level LogLevel) bool {
	return level >= l.GetLevel()
}

// 实现Logger接口的控制方法
func (l *ixLogger) Flush() error {
	if l.writer != nil {
		return l.writer.Sync()
	}
	return nil
}

func (l *ixLogger) Close() error {
	// 标记为停止
	atomic.StoreInt32(&l.running, 0)

	// 停止刷新定时器
	if l.flushTicker != nil {
		l.flushTicker.Stop()
	}

	// 发送停止信号
	close(l.stopChan)

	// 最后一次刷新
	if err := l.Flush(); err != nil {
		fmt.Fprintf(os.Stderr, "最终刷新失败: %v\n", err)
	}

	// 关闭写入器
	if l.writer != nil {
		return l.writer.Close()
	}

	return nil
}

// 实现Logger接口的钩子方法
func (l *ixLogger) AddHook(hook Hook) {
	l.mutex.Lock()
	defer l.mutex.Unlock()

	l.hooks = append(l.hooks, hook)
}

func (l *ixLogger) RemoveHook(hook Hook) {
	l.mutex.Lock()
	defer l.mutex.Unlock()

	for i, h := range l.hooks {
		if h == hook {
			l.hooks = append(l.hooks[:i], l.hooks[i+1:]...)
			break
		}
	}
}

// GetStats 获取统计信息
func (l *ixLogger) GetStats() *Stats {
	stats := *l.stats
	stats.Uptime = time.Since(l.startTime)

	// 获取缓冲区使用情况
	if asyncWriter, ok := l.writer.(*AsyncWriter); ok {
		stats.BufferUsage = int(asyncWriter.GetBufferUsage() * float64(l.config.BufferSize))
		stats.BufferSize = l.config.BufferSize
	}

	return &stats
}

// GetTraceManager 获取追踪管理器
func (l *ixLogger) GetTraceManager() *TraceManager {
	return l.traceManager
}

// contextLogger 带上下文的日志器
type contextLogger struct {
	logger Logger
	ctx    context.Context
}

func (cl *contextLogger) Trace(args ...interface{}) {
	if baseLogger, ok := cl.logger.(*ixLogger); ok {
		baseLogger.log(TRACE, fmt.Sprint(args...), nil, nil, cl.ctx)
	} else {
		cl.logger.Trace(args...)
	}
}

func (cl *contextLogger) Tracef(format string, args ...interface{}) {
	if baseLogger, ok := cl.logger.(*ixLogger); ok {
		baseLogger.log(TRACE, fmt.Sprintf(format, args...), nil, nil, cl.ctx)
	} else {
		cl.logger.Tracef(format, args...)
	}
}

func (cl *contextLogger) Debug(args ...interface{}) {
	if baseLogger, ok := cl.logger.(*ixLogger); ok {
		baseLogger.log(DEBUG, fmt.Sprint(args...), nil, nil, cl.ctx)
	} else {
		cl.logger.Debug(args...)
	}
}

func (cl *contextLogger) Debugf(format string, args ...interface{}) {
	if baseLogger, ok := cl.logger.(*ixLogger); ok {
		baseLogger.log(DEBUG, fmt.Sprintf(format, args...), nil, nil, cl.ctx)
	} else {
		cl.logger.Debugf(format, args...)
	}
}

func (cl *contextLogger) Info(args ...interface{}) {
	if baseLogger, ok := cl.logger.(*ixLogger); ok {
		baseLogger.log(INFO, fmt.Sprint(args...), nil, nil, cl.ctx)
	} else {
		cl.logger.Info(args...)
	}
}

func (cl *contextLogger) Infof(format string, args ...interface{}) {
	if baseLogger, ok := cl.logger.(*ixLogger); ok {
		baseLogger.log(INFO, fmt.Sprintf(format, args...), nil, nil, cl.ctx)
	} else {
		cl.logger.Infof(format, args...)
	}
}

func (cl *contextLogger) Warn(args ...interface{}) {
	if baseLogger, ok := cl.logger.(*ixLogger); ok {
		baseLogger.log(WARN, fmt.Sprint(args...), nil, nil, cl.ctx)
	} else {
		cl.logger.Warn(args...)
	}
}

func (cl *contextLogger) Warnf(format string, args ...interface{}) {
	if baseLogger, ok := cl.logger.(*ixLogger); ok {
		baseLogger.log(WARN, fmt.Sprintf(format, args...), nil, nil, cl.ctx)
	} else {
		cl.logger.Warnf(format, args...)
	}
}

func (cl *contextLogger) Error(args ...interface{}) {
	if baseLogger, ok := cl.logger.(*ixLogger); ok {
		baseLogger.log(ERROR, fmt.Sprint(args...), nil, nil, cl.ctx)
	} else {
		cl.logger.Error(args...)
	}
}

func (cl *contextLogger) Errorf(format string, args ...interface{}) {
	if baseLogger, ok := cl.logger.(*ixLogger); ok {
		baseLogger.log(ERROR, fmt.Sprintf(format, args...), nil, nil, cl.ctx)
	} else {
		cl.logger.Errorf(format, args...)
	}
}

func (cl *contextLogger) Fatal(args ...interface{}) {
	if baseLogger, ok := cl.logger.(*ixLogger); ok {
		baseLogger.log(FATAL, fmt.Sprint(args...), nil, nil, cl.ctx)
	} else {
		cl.logger.Fatal(args...)
	}
}

func (cl *contextLogger) Fatalf(format string, args ...interface{}) {
	if baseLogger, ok := cl.logger.(*ixLogger); ok {
		baseLogger.log(FATAL, fmt.Sprintf(format, args...), nil, nil, cl.ctx)
	} else {
		cl.logger.Fatalf(format, args...)
	}
}

// 委托其他方法
func (cl *contextLogger) WithContext(ctx context.Context) Logger {
	return &contextLogger{logger: cl.logger, ctx: ctx}
}

func (cl *contextLogger) WithField(key string, value interface{}) Logger {
	// 创建新的 fieldLogger，避免循环调用
	fields := map[string]interface{}{key: value}
	return &fieldLogger{
		logger: cl,
		fields: fields,
	}
}

func (cl *contextLogger) WithFields(fields map[string]interface{}) Logger {
	// 创建新的 fieldLogger，避免循环调用
	return &fieldLogger{
		logger: cl,
		fields: fields,
	}
}

func (cl *contextLogger) WithError(err error) Logger {
	// 创建新的 errorLogger，避免循环调用
	return &errorLogger{
		logger: cl,
		err:    err,
	}
}

func (cl *contextLogger) WithTrace(traceID, spanID, parentSpanID string) Logger {
	// 创建新的 traceLogger，避免循环调用
	return &traceLogger{
		logger:       cl,
		traceID:      traceID,
		spanID:       spanID,
		parentSpanID: parentSpanID,
	}
}

func (cl *contextLogger) SetLevel(level LogLevel)            { cl.logger.SetLevel(level) }
func (cl *contextLogger) GetLevel() LogLevel                 { return cl.logger.GetLevel() }
func (cl *contextLogger) IsLevelEnabled(level LogLevel) bool { return cl.logger.IsLevelEnabled(level) }
func (cl *contextLogger) Flush() error                       { return cl.logger.Flush() }
func (cl *contextLogger) Close() error                       { return cl.logger.Close() }
func (cl *contextLogger) AddHook(hook Hook)                  { cl.logger.AddHook(hook) }
func (cl *contextLogger) RemoveHook(hook Hook)               { cl.logger.RemoveHook(hook) }

// fieldLogger 带字段的日志器
type fieldLogger struct {
	logger Logger
	fields map[string]interface{}
}

func (fl *fieldLogger) Trace(args ...interface{}) {
	if baseLogger, ok := fl.logger.(*ixLogger); ok {
		baseLogger.log(TRACE, fmt.Sprint(args...), fl.fields, nil, nil)
	} else {
		// 直接调用底层logger的Trace方法，避免循环调用
		fl.logger.Trace(args...)
	}
}

func (fl *fieldLogger) Tracef(format string, args ...interface{}) {
	if baseLogger, ok := fl.logger.(*ixLogger); ok {
		baseLogger.log(TRACE, fmt.Sprintf(format, args...), fl.fields, nil, nil)
	} else {
		// 直接调用底层logger的Tracef方法，避免循环调用
		fl.logger.Tracef(format, args...)
	}
}

func (fl *fieldLogger) Debug(args ...interface{}) {
	if baseLogger, ok := fl.logger.(*ixLogger); ok {
		baseLogger.log(DEBUG, fmt.Sprint(args...), fl.fields, nil, nil)
	} else {
		// 直接调用底层logger的Debug方法，避免循环调用
		fl.logger.Debug(args...)
	}
}

func (fl *fieldLogger) Debugf(format string, args ...interface{}) {
	if baseLogger, ok := fl.logger.(*ixLogger); ok {
		baseLogger.log(DEBUG, fmt.Sprintf(format, args...), fl.fields, nil, nil)
	} else {
		// 直接调用底层logger的Debugf方法，避免循环调用
		fl.logger.Debugf(format, args...)
	}
}

func (fl *fieldLogger) Info(args ...interface{}) {
	if baseLogger, ok := fl.logger.(*ixLogger); ok {
		baseLogger.log(INFO, fmt.Sprint(args...), fl.fields, nil, nil)
	} else {
		// 直接调用底层logger的Info方法，避免循环调用
		fl.logger.Info(args...)
	}
}

func (fl *fieldLogger) Infof(format string, args ...interface{}) {
	if baseLogger, ok := fl.logger.(*ixLogger); ok {
		baseLogger.log(INFO, fmt.Sprintf(format, args...), fl.fields, nil, nil)
	} else {
		// 直接调用底层logger的Infof方法，避免循环调用
		fl.logger.Infof(format, args...)
	}
}

func (fl *fieldLogger) Warn(args ...interface{}) {
	if baseLogger, ok := fl.logger.(*ixLogger); ok {
		baseLogger.log(WARN, fmt.Sprint(args...), fl.fields, nil, nil)
	} else {
		// 直接调用底层logger的Warn方法，避免循环调用
		fl.logger.Warn(args...)
	}
}

func (fl *fieldLogger) Warnf(format string, args ...interface{}) {
	if baseLogger, ok := fl.logger.(*ixLogger); ok {
		baseLogger.log(WARN, fmt.Sprintf(format, args...), fl.fields, nil, nil)
	} else {
		// 直接调用底层logger的Warnf方法，避免循环调用
		fl.logger.Warnf(format, args...)
	}
}

func (fl *fieldLogger) Error(args ...interface{}) {
	if baseLogger, ok := fl.logger.(*ixLogger); ok {
		baseLogger.log(ERROR, fmt.Sprint(args...), fl.fields, nil, nil)
	} else {
		// 直接调用底层logger的Error方法，避免循环调用
		fl.logger.Error(args...)
	}
}

func (fl *fieldLogger) Errorf(format string, args ...interface{}) {
	if baseLogger, ok := fl.logger.(*ixLogger); ok {
		baseLogger.log(ERROR, fmt.Sprintf(format, args...), fl.fields, nil, nil)
	} else {
		// 直接调用底层logger的Errorf方法，避免循环调用
		fl.logger.Errorf(format, args...)
	}
}

func (fl *fieldLogger) Fatal(args ...interface{}) {
	if baseLogger, ok := fl.logger.(*ixLogger); ok {
		baseLogger.log(FATAL, fmt.Sprint(args...), fl.fields, nil, nil)
	} else {
		// 直接调用底层logger的Fatal方法，避免循环调用
		fl.logger.Fatal(args...)
	}
}

func (fl *fieldLogger) Fatalf(format string, args ...interface{}) {
	if baseLogger, ok := fl.logger.(*ixLogger); ok {
		baseLogger.log(FATAL, fmt.Sprintf(format, args...), fl.fields, nil, nil)
	} else {
		// 直接调用底层logger的Fatalf方法，避免循环调用
		fl.logger.Fatalf(format, args...)
	}
}

// 委托其他方法
func (fl *fieldLogger) WithContext(ctx context.Context) Logger {
	// 创建新的 contextLogger，避免循环调用
	return &contextLogger{
		logger: fl,
		ctx:    ctx,
	}
}

func (fl *fieldLogger) WithField(key string, value interface{}) Logger {
	newFields := make(map[string]interface{})
	for k, v := range fl.fields {
		newFields[k] = v
	}
	newFields[key] = value
	// 创建新的 fieldLogger，避免循环调用
	return &fieldLogger{
		logger: fl.logger,
		fields: newFields,
	}
}

func (fl *fieldLogger) WithFields(fields map[string]interface{}) Logger {
	newFields := make(map[string]interface{})
	for k, v := range fl.fields {
		newFields[k] = v
	}
	for k, v := range fields {
		newFields[k] = v
	}
	// 创建新的 fieldLogger，避免循环调用
	return &fieldLogger{
		logger: fl.logger,
		fields: newFields,
	}
}

func (fl *fieldLogger) WithError(err error) Logger {
	// 创建新的 errorLogger，避免循环调用
	return &errorLogger{
		logger: fl,
		err:    err,
	}
}

func (fl *fieldLogger) WithTrace(traceID, spanID, parentSpanID string) Logger {
	// 创建新的 traceLogger，避免循环调用
	return &traceLogger{
		logger:       fl,
		traceID:      traceID,
		spanID:       spanID,
		parentSpanID: parentSpanID,
	}
}

func (fl *fieldLogger) SetLevel(level LogLevel)            { fl.logger.SetLevel(level) }
func (fl *fieldLogger) GetLevel() LogLevel                 { return fl.logger.GetLevel() }
func (fl *fieldLogger) IsLevelEnabled(level LogLevel) bool { return fl.logger.IsLevelEnabled(level) }
func (fl *fieldLogger) Flush() error                       { return fl.logger.Flush() }
func (fl *fieldLogger) Close() error                       { return fl.logger.Close() }
func (fl *fieldLogger) AddHook(hook Hook)                  { fl.logger.AddHook(hook) }
func (fl *fieldLogger) RemoveHook(hook Hook)               { fl.logger.RemoveHook(hook) }

// errorLogger 带错误的日志器
type errorLogger struct {
	logger Logger
	err    error
}

func (el *errorLogger) Trace(args ...interface{}) {
	if baseLogger, ok := el.logger.(*ixLogger); ok {
		baseLogger.log(TRACE, fmt.Sprint(args...), nil, el.err, nil)
	} else {
		// 直接调用底层logger的Trace方法，避免再次包装错误
		el.logger.Trace(args...)
	}
}

func (el *errorLogger) Tracef(format string, args ...interface{}) {
	if baseLogger, ok := el.logger.(*ixLogger); ok {
		baseLogger.log(TRACE, fmt.Sprintf(format, args...), nil, el.err, nil)
	} else {
		// 直接调用底层logger的Tracef方法，避免再次包装错误
		el.logger.Tracef(format, args...)
	}
}

func (el *errorLogger) Debug(args ...interface{}) {
	if baseLogger, ok := el.logger.(*ixLogger); ok {
		baseLogger.log(DEBUG, fmt.Sprint(args...), nil, el.err, nil)
	} else {
		// 直接调用底层logger的Debug方法，避免再次包装错误
		el.logger.Debug(args...)
	}
}

func (el *errorLogger) Debugf(format string, args ...interface{}) {
	if baseLogger, ok := el.logger.(*ixLogger); ok {
		baseLogger.log(DEBUG, fmt.Sprintf(format, args...), nil, el.err, nil)
	} else {
		// 直接调用底层logger的Debugf方法，避免再次包装错误
		el.logger.Debugf(format, args...)
	}
}

func (el *errorLogger) Info(args ...interface{}) {
	if baseLogger, ok := el.logger.(*ixLogger); ok {
		baseLogger.log(INFO, fmt.Sprint(args...), nil, el.err, nil)
	} else {
		// 直接调用底层logger的Info方法，避免再次包装错误
		el.logger.Info(args...)
	}
}

func (el *errorLogger) Infof(format string, args ...interface{}) {
	if baseLogger, ok := el.logger.(*ixLogger); ok {
		baseLogger.log(INFO, fmt.Sprintf(format, args...), nil, el.err, nil)
	} else {
		// 直接调用底层logger的Infof方法，避免再次包装错误
		el.logger.Infof(format, args...)
	}
}

func (el *errorLogger) Warn(args ...interface{}) {
	if baseLogger, ok := el.logger.(*ixLogger); ok {
		baseLogger.log(WARN, fmt.Sprint(args...), nil, el.err, nil)
	} else {
		// 直接调用底层logger的Warn方法，避免再次包装错误
		el.logger.Warn(args...)
	}
}

func (el *errorLogger) Warnf(format string, args ...interface{}) {
	if baseLogger, ok := el.logger.(*ixLogger); ok {
		baseLogger.log(WARN, fmt.Sprintf(format, args...), nil, el.err, nil)
	} else {
		// 直接调用底层logger的Warnf方法，避免再次包装错误
		el.logger.Warnf(format, args...)
	}
}

func (el *errorLogger) Error(args ...interface{}) {
	if baseLogger, ok := el.logger.(*ixLogger); ok {
		baseLogger.log(ERROR, fmt.Sprint(args...), nil, el.err, nil)
	} else {
		// 直接调用底层logger的Error方法，避免再次包装错误
		el.logger.Error(args...)
	}
}

func (el *errorLogger) Errorf(format string, args ...interface{}) {
	if baseLogger, ok := el.logger.(*ixLogger); ok {
		baseLogger.log(ERROR, fmt.Sprintf(format, args...), nil, el.err, nil)
	} else {
		// 直接调用底层logger的Errorf方法，避免再次包装错误
		el.logger.Errorf(format, args...)
	}
}

func (el *errorLogger) Fatal(args ...interface{}) {
	if baseLogger, ok := el.logger.(*ixLogger); ok {
		baseLogger.log(FATAL, fmt.Sprint(args...), nil, el.err, nil)
	} else {
		// 直接调用底层logger的Fatal方法，避免再次包装错误
		el.logger.Fatal(args...)
	}
}

func (el *errorLogger) Fatalf(format string, args ...interface{}) {
	if baseLogger, ok := el.logger.(*ixLogger); ok {
		baseLogger.log(FATAL, fmt.Sprintf(format, args...), nil, el.err, nil)
	} else {
		// 直接调用底层logger的Fatalf方法，避免再次包装错误
		el.logger.Fatalf(format, args...)
	}
}

// 委托其他方法
func (el *errorLogger) WithContext(ctx context.Context) Logger {
	// 创建新的 contextLogger，避免循环调用
	return &contextLogger{
		logger: el,
		ctx:    ctx,
	}
}

func (el *errorLogger) WithField(key string, value interface{}) Logger {
	// 创建新的 fieldLogger，避免循环调用
	fields := map[string]interface{}{key: value}
	return &fieldLogger{
		logger: el,
		fields: fields,
	}
}

func (el *errorLogger) WithFields(fields map[string]interface{}) Logger {
	// 创建新的 fieldLogger，避免循环调用
	return &fieldLogger{
		logger: el,
		fields: fields,
	}
}

func (el *errorLogger) WithError(err error) Logger {
	return el.logger.WithError(err) // 新错误覆盖旧错误
}

func (el *errorLogger) WithTrace(traceID, spanID, parentSpanID string) Logger {
	// 创建新的 traceLogger，避免循环调用
	return &traceLogger{
		logger:       el,
		traceID:      traceID,
		spanID:       spanID,
		parentSpanID: parentSpanID,
	}
}

func (el *errorLogger) SetLevel(level LogLevel)            { el.logger.SetLevel(level) }
func (el *errorLogger) GetLevel() LogLevel                 { return el.logger.GetLevel() }
func (el *errorLogger) IsLevelEnabled(level LogLevel) bool { return el.logger.IsLevelEnabled(level) }
func (el *errorLogger) Flush() error                       { return el.logger.Flush() }
func (el *errorLogger) Close() error                       { return el.logger.Close() }
func (el *errorLogger) AddHook(hook Hook)                  { el.logger.AddHook(hook) }
func (el *errorLogger) RemoveHook(hook Hook)               { el.logger.RemoveHook(hook) }

// traceLogger 带追踪的日志器
type traceLogger struct {
	logger       Logger
	traceID      string
	spanID       string
	parentSpanID string
}

func (tl *traceLogger) Trace(args ...interface{}) {
	if baseLogger, ok := tl.logger.(*ixLogger); ok {
		// 创建临时上下文
		ctx := context.WithValue(context.Background(), TraceContextKey, &TraceContext{
			TraceID:      tl.traceID,
			SpanID:       tl.spanID,
			ParentSpanID: tl.parentSpanID,
		})
		baseLogger.log(TRACE, fmt.Sprint(args...), nil, nil, ctx)
	} else {
		// 直接调用底层logger的Trace方法，避免循环调用
		tl.logger.Trace(args...)
	}
}

func (tl *traceLogger) Tracef(format string, args ...interface{}) {
	if baseLogger, ok := tl.logger.(*ixLogger); ok {
		ctx := context.WithValue(context.Background(), TraceContextKey, &TraceContext{
			TraceID:      tl.traceID,
			SpanID:       tl.spanID,
			ParentSpanID: tl.parentSpanID,
		})
		baseLogger.log(TRACE, fmt.Sprintf(format, args...), nil, nil, ctx)
	} else {
		// 直接调用底层logger的Tracef方法，避免循环调用
		tl.logger.Tracef(format, args...)
	}
}

// 其他级别方法类似实现...
func (tl *traceLogger) Debug(args ...interface{}) {
	if baseLogger, ok := tl.logger.(*ixLogger); ok {
		ctx := context.WithValue(context.Background(), TraceContextKey, &TraceContext{
			TraceID:      tl.traceID,
			SpanID:       tl.spanID,
			ParentSpanID: tl.parentSpanID,
		})
		baseLogger.log(DEBUG, fmt.Sprint(args...), nil, nil, ctx)
	} else {
		// 直接调用底层logger的Debug方法，避免循环调用
		tl.logger.Debug(args...)
	}
}

func (tl *traceLogger) Debugf(format string, args ...interface{}) {
	if baseLogger, ok := tl.logger.(*ixLogger); ok {
		ctx := context.WithValue(context.Background(), TraceContextKey, &TraceContext{
			TraceID:      tl.traceID,
			SpanID:       tl.spanID,
			ParentSpanID: tl.parentSpanID,
		})
		baseLogger.log(DEBUG, fmt.Sprintf(format, args...), nil, nil, ctx)
	} else {
		// 直接调用底层logger的Debugf方法，避免循环调用
		tl.logger.Debugf(format, args...)
	}
}

func (tl *traceLogger) Info(args ...interface{}) {
	if baseLogger, ok := tl.logger.(*ixLogger); ok {
		ctx := context.WithValue(context.Background(), TraceContextKey, &TraceContext{
			TraceID:      tl.traceID,
			SpanID:       tl.spanID,
			ParentSpanID: tl.parentSpanID,
		})
		baseLogger.log(INFO, fmt.Sprint(args...), nil, nil, ctx)
	} else {
		// 直接调用底层logger的Info方法，避免循环调用
		tl.logger.Info(args...)
	}
}

func (tl *traceLogger) Infof(format string, args ...interface{}) {
	if baseLogger, ok := tl.logger.(*ixLogger); ok {
		ctx := context.WithValue(context.Background(), TraceContextKey, &TraceContext{
			TraceID:      tl.traceID,
			SpanID:       tl.spanID,
			ParentSpanID: tl.parentSpanID,
		})
		baseLogger.log(INFO, fmt.Sprintf(format, args...), nil, nil, ctx)
	} else {
		// 直接调用底层logger的Infof方法，避免循环调用
		tl.logger.Infof(format, args...)
	}
}

func (tl *traceLogger) Warn(args ...interface{}) {
	if baseLogger, ok := tl.logger.(*ixLogger); ok {
		ctx := context.WithValue(context.Background(), TraceContextKey, &TraceContext{
			TraceID:      tl.traceID,
			SpanID:       tl.spanID,
			ParentSpanID: tl.parentSpanID,
		})
		baseLogger.log(WARN, fmt.Sprint(args...), nil, nil, ctx)
	} else {
		// 直接调用底层logger的Warn方法，避免循环调用
		tl.logger.Warn(args...)
	}
}

func (tl *traceLogger) Warnf(format string, args ...interface{}) {
	if baseLogger, ok := tl.logger.(*ixLogger); ok {
		ctx := context.WithValue(context.Background(), TraceContextKey, &TraceContext{
			TraceID:      tl.traceID,
			SpanID:       tl.spanID,
			ParentSpanID: tl.parentSpanID,
		})
		baseLogger.log(WARN, fmt.Sprintf(format, args...), nil, nil, ctx)
	} else {
		// 直接调用底层logger的Warnf方法，避免循环调用
		tl.logger.Warnf(format, args...)
	}
}

func (tl *traceLogger) Error(args ...interface{}) {
	if baseLogger, ok := tl.logger.(*ixLogger); ok {
		ctx := context.WithValue(context.Background(), TraceContextKey, &TraceContext{
			TraceID:      tl.traceID,
			SpanID:       tl.spanID,
			ParentSpanID: tl.parentSpanID,
		})
		baseLogger.log(ERROR, fmt.Sprint(args...), nil, nil, ctx)
	} else {
		// 直接调用底层logger的Error方法，避免循环调用
		tl.logger.Error(args...)
	}
}

func (tl *traceLogger) Errorf(format string, args ...interface{}) {
	if baseLogger, ok := tl.logger.(*ixLogger); ok {
		ctx := context.WithValue(context.Background(), TraceContextKey, &TraceContext{
			TraceID:      tl.traceID,
			SpanID:       tl.spanID,
			ParentSpanID: tl.parentSpanID,
		})
		baseLogger.log(ERROR, fmt.Sprintf(format, args...), nil, nil, ctx)
	} else {
		// 直接调用底层logger的Errorf方法，避免循环调用
		tl.logger.Errorf(format, args...)
	}
}

func (tl *traceLogger) Fatal(args ...interface{}) {
	if baseLogger, ok := tl.logger.(*ixLogger); ok {
		ctx := context.WithValue(context.Background(), TraceContextKey, &TraceContext{
			TraceID:      tl.traceID,
			SpanID:       tl.spanID,
			ParentSpanID: tl.parentSpanID,
		})
		baseLogger.log(FATAL, fmt.Sprint(args...), nil, nil, ctx)
	} else {
		// 直接调用底层logger的Fatal方法，避免循环调用
		tl.logger.Fatal(args...)
	}
}

func (tl *traceLogger) Fatalf(format string, args ...interface{}) {
	if baseLogger, ok := tl.logger.(*ixLogger); ok {
		ctx := context.WithValue(context.Background(), TraceContextKey, &TraceContext{
			TraceID:      tl.traceID,
			SpanID:       tl.spanID,
			ParentSpanID: tl.parentSpanID,
		})
		baseLogger.log(FATAL, fmt.Sprintf(format, args...), nil, nil, ctx)
	} else {
		// 直接调用底层logger的Fatalf方法，避免循环调用
		tl.logger.Fatalf(format, args...)
	}
}

// 委托其他方法
func (tl *traceLogger) WithContext(ctx context.Context) Logger {
	// 创建新的 contextLogger，避免循环调用
	return &contextLogger{
		logger: tl,
		ctx:    ctx,
	}
}

func (tl *traceLogger) WithField(key string, value interface{}) Logger {
	// 创建新的 fieldLogger，避免循环调用
	fields := map[string]interface{}{key: value}
	return &fieldLogger{
		logger: tl,
		fields: fields,
	}
}

func (tl *traceLogger) WithFields(fields map[string]interface{}) Logger {
	// 创建新的 fieldLogger，避免循环调用
	return &fieldLogger{
		logger: tl,
		fields: fields,
	}
}

func (tl *traceLogger) WithError(err error) Logger {
	// 创建新的 errorLogger，避免循环调用
	return &errorLogger{
		logger: tl,
		err:    err,
	}
}

func (tl *traceLogger) WithTrace(traceID, spanID, parentSpanID string) Logger {
	return tl.logger.WithTrace(traceID, spanID, parentSpanID)
}

func (tl *traceLogger) SetLevel(level LogLevel)            { tl.logger.SetLevel(level) }
func (tl *traceLogger) GetLevel() LogLevel                 { return tl.logger.GetLevel() }
func (tl *traceLogger) IsLevelEnabled(level LogLevel) bool { return tl.logger.IsLevelEnabled(level) }
func (tl *traceLogger) Flush() error                       { return tl.logger.Flush() }
func (tl *traceLogger) Close() error                       { return tl.logger.Close() }
func (tl *traceLogger) AddHook(hook Hook)                  { tl.logger.AddHook(hook) }
func (tl *traceLogger) RemoveHook(hook Hook)               { tl.logger.RemoveHook(hook) }
